package model

import (
	"encoding/json"
	"fmt"
	"nt-order/common"
	"nt-order/conf"
	"time"
)

type OrderAuth struct {
	Id          int64      `json:"id"`
	Staff_name  string     `json:"staff_name"`
	Platform    []string   `json:"platform"`
	Shop_name   []ShopName `json:"shop_name"`
	Field       []Filed    `json:"field"`
	Update_user string     `json:"update_user"`
	Create_user string     `json:"create_user"`
	Created_at  time.Time  `json:"created_at"`
	Updated_at  time.Time  `json:"updated_at"`
	Staff_id    string     `json:"staff_id"`
}

type ShopName struct {
	Pname    string     `json:"pName"`
	Type     bool       `json:"type"`
	IconType bool       `json:"icon_type"`
	List     []ShopList `json:"list"`
}

type ShopList struct {
	ShopName string `json:"shopName"`
	Select   bool   `json:"select"`
	Show     bool   `json:"show"`
}

type Filed struct {
	C_name string      `json:"c_name"`
	E_name string      `json:"e_name"`
	List   []FieldList `json:"list"`
}

type FieldList struct {
	Key    string `json:"key"`
	Val    string `json:"val"`
	Select bool   `json:"select"`
}

func (m *OrderAuth) First(staffId string) *OrderAuth {
	type OrderAuthRs struct {
		Id          int64     `json:"id"`
		Staff_name  string    `json:"staff_name"`
		Platform    string    `json:"platform"`
		Shop_name   string    `json:"shop_name"`
		Field       string    `json:"field"`
		Update_user string    `json:"update_user"`
		Create_user string    `json:"create_user"`
		Created_at  time.Time `json:"created_at"`
		Updated_at  time.Time `json:"updated_at"`
		Staff_id    string    `json:"staff_id"`
	}
	res := OrderAuthRs{}
	db := conf.GetDb()
	get, err := db.SQL("select * from order_auth where staff_id=?", staffId).Get(&res)
	if err != nil {
		panic(err)
	}

	if !get {
		return nil
	}

	shopNames := make([]ShopName, 0)
	err = json.Unmarshal([]byte(res.Shop_name), &shopNames)
	if err != nil {
		panic(err)
	}

	fields := make([]Filed, 0)
	err = json.Unmarshal([]byte(res.Field), &fields)
	if err != nil {
		panic(err)
	}

	platforms := make([]string, 0)
	err = json.Unmarshal([]byte(res.Platform), &platforms)
	if err != nil {
		panic(err)
	}

	return &OrderAuth{
		Id:          res.Id,
		Staff_name:  res.Staff_name,
		Platform:    platforms,
		Shop_name:   shopNames,
		Field:       fields,
		Update_user: res.Update_user,
		Create_user: res.Create_user,
		Created_at:  res.Created_at,
		Updated_at:  res.Updated_at,
		Staff_id:    res.Staff_id,
	}
}

func (m *OrderAuth) Where(staffId string) (string, []interface{}) {
	res := m.First(staffId)

	where := ""
	bind := make([]interface{}, 0)

	i := 0
	if len(res.Shop_name) > 0 {
		shopKv := m.GetShopKV(false)
		for _, shopName := range res.Shop_name {
			if i > 0 {
				where += " or "
			}

			shopList := make([]int, 0)
			for _, item := range shopName.List {
				for k, v := range shopKv {
					if v == item.ShopName {
						shopList = append(shopList, k)
						break
					}
				}
			}
			where += " (platform=? "
			bind = append(bind, shopName.Pname)
			if len(shopList) > 0 {
				where += " and shop_id in(" + common.FillQuestionnaire(len(shopList)) + ")"
				for _, shop_id := range shopList {
					bind = append(bind, shop_id)
				}
			}
			where += ")"
			i = i + 1
		}
	}

	if where != "" {
		where = " and ( " + where + " ) "
	}

	return where, bind
}

func (m *OrderAuth) GetShopKV(isUser bool) map[int]string {
	token := "order:shop_list_kv"
	if isUser {
		token = "order:shop_list_kv_user"
	}
	result := make(map[int]string)
	redis := conf.GetRedis()
	data, err := redis.Get(token)
	if err != nil || len(data) == 0 {
		type CurlRs struct {
			Code int `json:"code"`
			Data struct {
				Authorization string `json:"authorization"`
			} `json:"data"`
		}
		curlRs := new(CurlRs)
		curl, err := common.Curl("GET", conf.Env.Url.AuthUrl+"/rest/authorization/authorize", map[string]string{"appKey": conf.Env.Url.AppKey, "appSecret": conf.Env.Url.AppSecret}, nil)
		if err != nil {
			panic(err)
		}
		err = json.Unmarshal(curl, curlRs)
		if err != nil {
			panic(err)
		}

		headers := make(map[string]string)
		if curlRs.Code == 0 {
			headers["Authorization"] = "1b388e2c6b4383e5f3ec7d6e7d63e6bd"
			headers["UserID"] = "284037244136324166"
		}
		authStaffData, err := common.Curl("GET", conf.Env.Url.ShopUrl+"/shop/account?enable=0&platform=&offset=0&size=10000", nil, headers)
		if err != nil {
			panic(err)
		}

		type AuthStaff struct {
			Code int    `json:"code"`
			Msg  string `json:"msg"`
			Data struct {
				Accounts []struct {
					Id       int    `json:"id"`
					ShopName string `json:"shopName"`
					UserId   string `json:"userId"`
				} `json:"accounts"`
			} `json:"data"`
		}

		authStaff := new(AuthStaff)
		err = json.Unmarshal(authStaffData, authStaff)
		if err != nil {
			panic(err)
		}

		if authStaff.Code != 0 {
			panic(fmt.Errorf("code:%d,msg:%s", authStaff.Code, authStaff.Msg))
		}

		for _, account := range authStaff.Data.Accounts {
			if isUser {
				result[account.Id] = account.UserId
			} else {
				result[account.Id] = account.ShopName
			}
		}

		marshal, err := json.Marshal(result)
		if err != nil {
			panic(err)
		}

		_ = redis.Set(token, string(marshal), time.Second*600)
	} else {
		err := json.Unmarshal([]byte(data), &result)
		if err != nil {
			panic(err)
		}
	}

	return result
}
